package com.tubruk.todo.activity;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import com.tubruk.todo.activity.R;
import com.tubruk.todo.Global;
import com.tubruk.todo.PopMenu;
import com.tubruk.todo.TaskContent;
import com.tubruk.todo.Todos;
import com.tubruk.todo.database.TodoAdapter;
import com.tubruk.util.dialog.DateTimePicker;
import com.tubruk.util.dialog.ListMenu;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;

import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TableRow;

public class AddItemActivity extends Activity {

	private static final String PRIORITIES = "PRIORITIES";
	
	// Menu item ids
	private static final int MENU_ITEM_SAVE = Menu.FIRST;
	private static final int MENU_ITEM_CANCEL = Menu.FIRST + 1;
	
	//private EditText titleET = null;
	private TaskContent todo = null;

	private boolean isDateSet = false;
	
	private ArrayList<PopMenu> priorities = null;
	
	private static final int DATE_DIALOG_ID = 1;
	private static final int PRIORITY_DIALOG_ID = 2;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		todo = new TaskContent();
		setContentView(R.layout.additem_main);
		
		CheckBox priorityCB = (CheckBox) this.findViewById(R.id.priorityChk);
		priorityCB.setOnClickListener(new PriorityClickHandler());
		
		CheckBox dueDateCB = (CheckBox) this.findViewById(R.id.dueDateChk);
		dueDateCB.setOnClickListener(new DueDateClickHandler());
			
		Button backBtn = (Button) this.findViewById(R.id.back);
		backBtn.setOnClickListener(new BackButtonHandler());
		
		Button saveBtn = (Button) this.findViewById(R.id.savetask);
		saveBtn.setOnClickListener(new SaveButtonHandler());
		
		Button btn = (Button) AddItemActivity.this.findViewById(R.id.priorityBtn);
		btn.setVisibility(View.INVISIBLE);
		
		priorities = new ArrayList<PopMenu>();
		priorities.add(new PopMenu(PopMenu.NO_IMAGE, "  Low", Global.PRIORITY_COLOR_LOW));
		priorities.add(new PopMenu(PopMenu.NO_IMAGE, "  Medium", Global.PRIORITY_COLOR_MEDIUM));
		priorities.add(new PopMenu(PopMenu.NO_IMAGE, "  High", Global.PRIORITY_COLOR_HIGH));
		
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			if (bundle.get(Todos.Todo.PARENT_ID) != null) {
				todo.setParentId(((Integer)bundle.get(Todos.Todo.PARENT_ID)).intValue());
			} else if (bundle.get(Todos.Todo._ID) != null) {
				int id = ((Integer)bundle.get(Todos.Todo.PARENT_ID)).intValue();
				todo = TodoAdapter.getTaskContent(getContentResolver(), id);
			}
		}
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	  //ignore orientation change
	  super.onConfigurationChanged(newConfig);
	}

	
	private class BackButtonHandler implements View.OnClickListener {
		public void onClick(View v) {
			checkChanges();
		}
	}
	
	private class SaveButtonHandler implements View.OnClickListener {
		public void onClick(View v) {
			saveValues();
			finishActivity();
		}
	}

	//add menu options
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		// This is our one standard application action -- inserting a
		// new note into the list.
		menu.add(0, MENU_ITEM_SAVE, 0, R.string.addmenu_save).setIcon(
				android.R.drawable.ic_menu_add);
		menu.add(0, MENU_ITEM_CANCEL, 0, R.string.addmenu_cancel).setIcon(
				android.R.drawable.ic_menu_close_clear_cancel);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// handle cancel menu
		case MENU_ITEM_CANCEL:
			checkChanges();
			return true;
		case MENU_ITEM_SAVE:
			saveValues();
			// Stop the activity
			finishActivity();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private int saveValues() {
		getValues();
		return TodoAdapter.insertNewRow(getContentResolver(), todo);
	
	}
	
	//check any value changes
	private boolean hasChanged() {
		getValues();
		String title = todo.getTitle();
		if (title == null || title.length() == 0) {
			return false;
		}
		return true;
	}
	
	private void getValues() {
		
		EditText titleET = (EditText) this.findViewById(R.id.titleTxt);
		EditText noteET = (EditText) this.findViewById(R.id.descTxt);
		
		todo.setTitle(titleET.getText().toString());
		todo.setNote(noteET.getText().toString());
		
		//other values are maintained with event handler
		
		
	}
	
	private void checkChanges() {
		if (hasChanged()) {
			new AlertDialog.Builder(this).setIcon(
				android.R.drawable.ic_dialog_alert)
				.setTitle("Are sure")
				.setMessage("Are you really sure")
				.setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int which) {
							// Stop the activity
							cancelActivity();
						}
					})
				.setNegativeButton("No", null).show();
		} else {
			// Stop the activity
			cancelActivity();
		}
	}
	
	private void finishActivity(){
		Intent resultIntent = new Intent();
		//resultIntent.putExtra(PUBLIC_STATIC_STRING_IDENTIFIER, tabIndexValue);
		setResult(Activity.RESULT_OK, resultIntent);
		finish();
	}
	
	private void cancelActivity(){
		Intent resultIntent = new Intent();
		//resultIntent.putExtra(PUBLIC_STATIC_STRING_IDENTIFIER, tabIndexValue);
		setResult(Activity.RESULT_CANCELED, resultIntent);
		finish();
	}

	//handle back button, should check if item already has values
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Handle the back button
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// Ask the user if they want to quit
			checkChanges();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	
	private class PriorityClickHandler implements View.OnClickListener {
		
		public void onClick(View v) {
			
			AddItemActivity act = AddItemActivity.this;
			
			CheckBox cb = (CheckBox) act.findViewById(R.id.priorityChk);
			
			LayoutInflater vi = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        
			if (cb.isChecked()) {
				showDialog(AddItemActivity.PRIORITY_DIALOG_ID);
			}else {
				Button btn = (Button) AddItemActivity.this.findViewById(R.id.priorityBtn);
				btn.setVisibility(View.INVISIBLE);
				
				todo.setPriority(TaskContent.PRIORITY_NONE);
			}
	       
			
		}
	}
	
	private class DueDateClickHandler implements View.OnClickListener {
		public void onClick(View v){
			AddItemActivity act = AddItemActivity.this;
			
			CheckBox cb = (CheckBox) act.findViewById(R.id.dueDateChk);
			
			if (cb.isChecked()) {
				showDialog(DATE_DIALOG_ID);
			}else {
				//make sure the view is removed
				//LayoutInflater vi = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		        TableRow tblRow = (TableRow) AddItemActivity.this.findViewById(R.id.DueDateTblRow);
				
		        tblRow.removeAllViews();
		        act.isDateSet = false;
		        act.todo.setDueDate(null);
			}
			//new DatePickerDialog(AddItemActivity.this, dateListener, year, month, day);
		}
	}
	
	
	private class DateTimePickerListener implements DateTimePicker.DateTimePickerListener {
		public void okClicked(Calendar calendar){
			
			
			LayoutInflater vi = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        TableRow tblRow = (TableRow) AddItemActivity.this.findViewById(R.id.DueDateTblRow);
			
			View vTemp = vi.inflate(R.layout.duedate_text, null);
			tblRow.removeAllViews();
			tblRow.addView(vTemp);
			
			Button dueDate = (Button) AddItemActivity.this.findViewById(R.id.DueDateBtn);
			dueDate.setText(DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
					.format(calendar.getTime()));				
			dueDate.setOnClickListener(new DueDateClickHandler());
	
			AddItemActivity.this.isDateSet = true;
			AddItemActivity.this.todo.setDueDate(calendar.getTime());
		}
		public void cancelClicked(){
			if (!AddItemActivity.this.isDateSet){
				CheckBox dueDateCB = (CheckBox) AddItemActivity.this.findViewById(R.id.dueDateChk);
				dueDateCB.setChecked(false);		
			}
		}
	}

	protected Dialog onCreateDialog(int id){
		switch(id) {
		case DATE_DIALOG_ID:
			return new DateTimePicker(this, new DateTimePickerListener());
		case PRIORITY_DIALOG_ID:
			return new ListMenu(this, new ListMenuListener(), priorities, AddItemActivity.PRIORITIES);
		}
		
		return null;
		
	}
	
	private class ListMenuListener implements ListMenu.ListMenuListener {

		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
				Button imgBtn = (Button) AddItemActivity.this.findViewById(R.id.priorityBtn);
				if (arg2 == 0){
					todo.setPriority(TaskContent.PRIORITY_LOW);
					imgBtn.setBackgroundColor(Global.PRIORITY_COLOR_LOW);
					//imgBtn.setBackgroundResource(R.drawable.greenoff);
					imgBtn.setText("Low");
				}else if (arg2 == 1){
					todo.setPriority(TaskContent.PRIORITY_MEDIUM);
					imgBtn.setBackgroundColor(Global.PRIORITY_COLOR_MEDIUM);
					//imgBtn.setBackgroundResource(R.drawable.yellowoff);
					imgBtn.setText("Medium");
				}else if (arg2 == 2){
					todo.setPriority(TaskContent.PRIORITY_HIGH);
					imgBtn.setBackgroundColor(Global.PRIORITY_COLOR_HIGH);
					//imgBtn.setBackgroundResource(R.drawable.redoff);
					imgBtn.setText("High");
				}
				imgBtn.setVisibility(View.VISIBLE);
				imgBtn.setOnClickListener(new PriorityClickHandler());
				
				
		}
    	
    }

}
